import os
import time

from main import settings
from utils.Conf import Configuration
from utils.ssh_utils import SCPMet
from utils.views import ReturnClass
from general.deploy.dao import download_event_in

class SshExec():
    def __init__(self, host_info, deploy_event_ids):
        self.host_info = host_info
        self.deploy_event_ids = deploy_event_ids

    def set_ssh(self):
        self.ssh = SCPMet()
        self.ssh.set_info(self.host_info)
        self.ssh.cp_connect()

    def ssh_close(self):
        self.ssh.close()

    def host_action_execute(self, host_execute_infos, start_download_enent_step_code):

        # 按权重排序执行命令
        host_execute_infos = sorted(host_execute_infos, key=lambda i: i['order_by'], reverse=True)

        # 按顺序执行命令
        for host_execute_info in host_execute_infos:
            time.sleep(1)
            download_event_in(self.deploy_event_ids,
                              '正在执行%s(%s)' % (
                                  host_execute_info['system_action_name'], host_execute_info['system_content']), '2', start_download_enent_step_code)
            command_result = self.ssh.execcmd(host_execute_info['system_content'])
            if ReturnClass.if_ok(command_result):
                download_event_in(self.deploy_event_ids,
                                '执行%s成功(%s)' % (
                                host_execute_info['system_action_name'], host_execute_info['system_content']), '1', start_download_enent_step_code)
            else:
                other_info = ""
                if host_execute_info['ignore_error'] == 1:
                    other_info = "【被标记忽略的错误，跳过】"

                download_event_in(self.deploy_event_ids,
                                '执行%s失败(%s:%s%s)' % (
                                host_execute_info['system_action_name'], host_execute_info['system_content'],
                                command_result['data'], other_info), '0', start_download_enent_step_code)

                if not other_info:
                    self.ssh_close()
                    return False

            start_download_enent_step_code += 1

        return start_download_enent_step_code

    def get_file(self, hots_path, local_file_path, file_type, start_download_enent_step_code):
        """
        拷贝打包文件到平台目录
        @param hots_path:
        @param local_path:
        @return:
        """
        file_name = os.path.basename(hots_path)

        os.makedirs(os.path.join(local_file_path, file_type), exist_ok=True)
        local_path = os.path.join(local_file_path ,file_type, file_name)
        download_event_in(self.deploy_event_ids,
                          "正在下载文件到平台",
                          '2', download_enent_step_code=start_download_enent_step_code)

        try:
            local_path_ = self.ssh.get_file(hots_path, local_path)

            download_event_in(self.deploy_event_ids, '下载文件到平台成功',
                              '3', download_enent_step_code=start_download_enent_step_code)

            download_event_in(self.deploy_event_ids, '{"file_type":"%s","file_name":"%s","info":"下载文件到平台"}' % (file_type, file_name),
                              '4', download_enent_step_code=start_download_enent_step_code,
                              download_event_type="platform_file_save_info")

        except Exception as e:
            download_event_in(self.deploy_event_ids, '下载文件到平台失败(%s)' %str(e),
                              '0', download_enent_step_code=start_download_enent_step_code)
            return False

        start_download_enent_step_code += 1

        return start_download_enent_step_code


    def put_file_image(self, local_file_path, start_download_enent_step_code):
        self.file_name = os.path.basename(local_file_path)
        hots_path = os.path.join('/tmp' + '/%s' %self.file_name)
        download_event_in(self.deploy_event_ids,
                          "开始上传文件到标记服务器",
                          '4', download_enent_step_code=start_download_enent_step_code, download_event_type='platform_file_save_info')
        exec_info = self.ssh.put_file(local_file_path, hots_path)
        return True

    def put_file_image_progress(self, start_download_enent_step_code):
        download_event_in(self.deploy_event_ids,
                          '{"percents": %s, "file_name":"%s", "info":"下载文件到平台"}' % (self.ssh.percents, self.file_name),
                          '4', download_enent_step_code=start_download_enent_step_code, download_event_type='platform_file_save_info')
        if not int(self.ssh.percents) == 100:
            time.sleep(2)
            self.put_file_image_progress(start_download_enent_step_code)

        return True